package com.runen.infinitemovement.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.activity.ArmyGroupManagerActivity;
import com.runen.infinitemovement.activity.BodyDataActivity;
import com.runen.infinitemovement.activity.CompanyCricleActivity;
import com.runen.infinitemovement.activity.DayTaskActivity;
import com.runen.infinitemovement.activity.InviteFriendsActivity;
import com.runen.infinitemovement.activity.LoginActivity2;
import com.runen.infinitemovement.activity.MyActivity;
import com.runen.infinitemovement.activity.MyCredentialActivity;
import com.runen.infinitemovement.activity.MyFocusActivity;
import com.runen.infinitemovement.activity.MyHozomActivity;
import com.runen.infinitemovement.activity.MyMedalActivity;
import com.runen.infinitemovement.activity.MyMessageActivity;
import com.runen.infinitemovement.activity.MySuggestActivity;
import com.runen.infinitemovement.activity.MyTeamActivityV2;
import com.runen.infinitemovement.activity.PersonCenterActivity;
import com.runen.infinitemovement.activity.SettingActivity;
import com.runen.infinitemovement.activity.WebActivity;
import com.runen.infinitemovement.adapter.MeUtilsAdapter;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.MeInfoEntity;
import com.runen.infinitemovement.model.entity.MeUtilsEntity;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.TimeUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.rci_my_header)
    RoundedCornersImage rciMyHeader;
    @BindView(R.id.rl_heard)
    RelativeLayout rlHeard;
    @BindView(R.id.tv_my_name)
    TextView tvMyName;
    @BindView(R.id.rl_top)
    RelativeLayout rlTop;
    @BindView(R.id.ll_sports_info)
    LinearLayout llSportsInfo;
    @BindView(R.id.iv_msg)
    ImageView iv_msg;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.my_activity)
    LinearLayout myActivity;
    @BindView(R.id.my_sports_data)
    LinearLayout mySportsData;
    @BindView(R.id.tv_company_name)
    TextView tvCompanyName;
    @BindView(R.id.tv_myself_activity_num)
    TextView tvMyselfActivityNum;
    @BindView(R.id.tv_myself_activity_time)
    TextView tvMyselfActivityTime;
    @BindView(R.id.tv_myself_sports_num)
    TextView tvMyselfSportsNum;
    @BindView(R.id.tv_myself_sports_time)
    TextView tvMyselfSportsTime;
    @BindView(R.id.iv_sex)
    ImageView ivSex;
    @BindView(R.id.rcv_utils)
    RecyclerView rcvUtils;
    private View view;
    private List<MeUtilsEntity> list = new ArrayList<>();
    private MeUtilsAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == view) {
            view = inflater.inflate(R.layout.fragment_me_1, container, false);
            ButterKnife.bind(this, view);
            EventBus.getDefault().register(this);
            srl.setOnRefreshListener(this);
        }
        initView();
        initData();
        return view;
    }

    private void initView() {
        NotchTools.getFullScreenTools().translucentStatusBar(getActivity(), new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
                iv_msg.setPadding(iv_msg.getPaddingLeft(),
                        CommonUtil.getStatusBarHeight(getActivity()) + iv_msg.getPaddingTop() - CommonUtil.dp2px(getActivity(), 20)
                        , iv_msg.getPaddingRight(), iv_msg.getPaddingBottom());
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rlTop.getLayoutParams();
                layoutParams.topMargin = layoutParams.topMargin + CommonUtil.getStatusBarHeight(getActivity()) - CommonUtil.dp2px(getActivity(), 20);
                rlTop.setLayoutParams(layoutParams);
            }
        });
        //工具
//        list.add(new MeUtilsEntity(R.mipmap.ico_me_utils_jtgl, "军团管理", 1));
        list.add(new MeUtilsEntity(R.mipmap.ico_me_utils_wdzs, "我的证书", 2));
        list.add(new MeUtilsEntity(R.mipmap.ico_me_utils_wdxz, "我的勋章", 3));
        list.add(new MeUtilsEntity(R.mipmap.ico_me_utils_wdwz, "我的物资", 4));
        list.add(new MeUtilsEntity(R.mipmap.ico_me_utils_wdgz, "我的关注", 5));
        list.add(new MeUtilsEntity(R.mipmap.ico_me_utils_stsj, "身体数据", 6));
        list.add(new MeUtilsEntity(R.mipmap.ico_me_utils_yjfk, "意见反馈", 7));
        list.add(new MeUtilsEntity(R.mipmap.ico_me_utils_sz, "设置", 8));
        adapter = new MeUtilsAdapter(getActivity());
        LinearLayoutManager llm = new GridLayoutManager(getActivity(), 4);
        rcvUtils.setLayoutManager(llm);
        rcvUtils.setAdapter(adapter);
        adapter.addData(list);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Intent intent = new Intent();
                switch (((MeUtilsEntity) adapter.getData().get(position)).type) {
                    case 1:
                        intent.setClass(getActivity(), ArmyGroupManagerActivity.class);
                        startActivity(intent);
                        break;
                    case 2:
                        intent.setClass(getActivity(), MyCredentialActivity.class);
                        startActivity(intent);
                        break;
                    case 3:
                        intent.setClass(getActivity(), MyMedalActivity.class);
                        startActivity(intent);
                        break;
                    case 4:
                        intent.setClass(getActivity(), WebActivity.class);
                        intent.putExtra("LINK_URL", String.format(Constant.H5_MY_GOODS, UserAPI.getUserToken()));
                        startActivity(intent);
                        break;
                    case 5:
                        intent.setClass(getActivity(), MyFocusActivity.class);
                        startActivity(intent);
                        break;
                    case 6:
                        intent.setClass(getActivity(), BodyDataActivity.class);
                        startActivity(intent);
                        break;
                    case 7:
                        intent.setClass(getActivity(), MySuggestActivity.class);
                        startActivity(intent);
                        break;
                    case 8:
                        intent.setClass(getActivity(), SettingActivity.class);
                        startActivity(intent);
                        break;
                }
            }
        });
    }

    private void initData() {
        srl.setRefreshing(true);
        new UserAPI().meInfo(new BaseResultCallback<MeInfoEntity>() {
            @Override
            public void onResponse(MeInfoEntity response) {
                srl.setRefreshing(false);
                if (response.data != null) {
                    String str = "上次记录%s";
                    if (!TextUtils.isEmpty(response.data.headImgUrl)) {
                        GlideUtils.loadImage(getActivity(), response.data.headImgUrl, rciMyHeader);
                    }
                    if (response.data.sex == 0) {
                        ivSex.setImageResource(R.mipmap.iv_sex_woman);
                    } else {
                        ivSex.setImageResource(R.mipmap.ico_sex_man);
                    }
                    tvMyName.setText(response.data.nickname);
                    tvCompanyName.setText(response.data.companyName);
                    if (response.data.mySelfInfoActivityDto != null) {
                        tvMyselfActivityNum.setText(response.data.mySelfInfoActivityDto.times + "");
                        tvMyselfActivityTime.setText(String.format(str, TimeUtil.converFromSecondTime(TimeUtil.getDateTimeToLong(response.data.mySelfInfoActivityDto.lastTime))));
                    }
                    if (response.data.myselfInfoSportDto != null) {
                        tvMyselfSportsNum.setText(String.valueOf(CommonUtil.Double2position(response.data.myselfInfoSportDto.mileage)));
                        tvMyselfSportsTime.setText(String.format(str, TimeUtil.converFromSecondTime(TimeUtil.getDateTimeToLong(response.data.myselfInfoSportDto.finishTime))));
                    }
                    //如果是军团长
                    if (response.data.leaderStatus) {
                        if (adapter.getData().get(0).type != 1)
                            adapter.addData(0, new MeUtilsEntity(R.mipmap.ico_me_utils_jtgl, "军团管理", 1));
                    } else {
                        if (adapter.getData().get(0).type == 1) {
                            adapter.remove(adapter.getData().get(0));
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(getActivity(), LoginActivity2.class));
                    }
                }
                super.onError(e, body);
                srl.setRefreshing(false);
            }

            @Override
            public void onComplete() {
                super.onComplete();
                srl.setRefreshing(false);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventBusEntity event) {
        switch (event.getMsg()) {
            case 5:
            case 99:
            case EventBusEntity.CODE_104:
            case EventBusEntity.CODE_105:
            case EventBusEntity.CODE_106:
                initData();
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.rl_top, R.id.iv_msg, R.id.my_sports_data, R.id.my_activity, R.id.rl_invit,
            R.id.tv_jrrw, R.id.tv_wdhz, R.id.tv_wdtd, R.id.tv_jtyd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_top:
                Intent intent = new Intent(getActivity(), PersonCenterActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_msg://我的消息
                Intent intent5 = new Intent(getActivity(), MyMessageActivity.class);
                startActivity(intent5);
                break;
            case R.id.my_activity://我的活动
                Intent intent8 = new Intent(getActivity(), MyActivity.class);
                startActivity(intent8);
                break;
            case R.id.my_sports_data://运动记录
                Intent inte = new Intent(getActivity(), WebActivity.class);
                String url = Constant.SPORTS_RECORD;
                inte.putExtra("LINK_URL", String.format(url, UserAPI.getUserToken()));
                startActivity(inte);
                break;
            case R.id.rl_invit:
                startActivity(new Intent(getActivity(), InviteFriendsActivity.class));
                break;
            case R.id.tv_jrrw:
                startActivity(new Intent(getActivity(), DayTaskActivity.class));
                break;
            case R.id.tv_wdhz:
                startActivity(new Intent(getActivity(), MyHozomActivity.class));
                break;
            case R.id.tv_wdtd:
                startActivity(new Intent(getActivity(), MyTeamActivityV2.class));
                break;
            case R.id.tv_jtyd:
                startActivity(new Intent(getActivity(), CompanyCricleActivity.class));
                break;
        }
    }

    @Override
    public void onRefresh() {
        initData();
    }
}
